import './assets/main.css'

import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import { ElMessage } from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'

// 配置 axios
axios.defaults.baseURL = 'http://localhost:8000'  // 后端API地址
axios.defaults.timeout = 10000  // 请求超时时间
axios.defaults.headers.common['Content-Type'] = 'application/json'

// 添加响应拦截器
axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response) {
      // 处理服务器返回的错误
      const { status, data } = error.response
      let message = '请求失败'
      if (data && data.detail) {
        message = data.detail
      }
      ElMessage.error(`${message} (${status})`)
    } else if (error.request) {
      // 请求发出但没有收到响应
      ElMessage.error('服务器无响应，请检查网络连接')
    } else {
      // 请求配置出错
      ElMessage.error('请求配置错误')
    }
    return Promise.reject(error)
  }
)

const app = createApp(App)

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

app.use(ElementPlus)
app.use(router)

// 将 axios 添加到全局属性
app.config.globalProperties.$axios = axios

// 将 ElMessage 添加到全局属性
app.config.globalProperties.$message = ElMessage

app.mount('#app')
